<template>
	<el-container>
		<el-header>
			<el-form :model="searchmodel" :inline="true" class="demo-form-inline" style="width: 70%; float: left;">
				<el-form-item label="ISBN">
					<el-input placeholder="ISBN" v-model="searchmodel.isbn" @input="change($event)"></el-input>
				</el-form-item>
				<el-form-item label="书名">
					<el-input placeholder="读书名称" v-model="searchmodel.title" @input="change($event)"></el-input>
				</el-form-item>
				<el-form-item label="读书状态">
					<el-select v-model="searchmodel.state" placeholder="请选择状态">
						<el-option label="所有" value="-1"></el-option>
						<el-option label="在馆" value="1"></el-option>
						<el-option label="外借" value="0"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getBooks()" icon="el-icon-search">搜索</el-button>
				</el-form-item>
			</el-form>
			<div style="float: right;">
				<el-button type="success" icon="el-icon-circle-plus" @click="addBook()"></el-button>
			</div>
		</el-header>
		<el-main style="padding: unset;">
			<el-table :max-height="tableHeight" :data="tableData" border>
				<el-table-column fixed type="expand">
					<template slot-scope="props">
						<el-container>
							<el-row>
								<el-col :lg="4" :sm="4" :xs="5" :offset="1">
									<img height="100" width="100" v-if="!props.row.cover" src="~@/assets/logo.png"
										alt="electron-vue" />
									<img height="100" width="100" v-if="props.row.cover" src="props.row.cover"
										alt="electron-vue" />
								</el-col>
								<el-col :lg="6" :sm="6" :xs="6" :offset="1">
									<el-form label-position="left" inline class="demo-table-expand">
										<el-form-item label="作者:">
											<span>{{ props.row.title }}</span>
										</el-form-item>
										<el-form-item label="ISBN:">
											<span>{{ props.row.isbn }}</span>
										</el-form-item>
										<el-form-item label=" 总页数:">
											<span>{{ props.row.pageCount }}</span>
										</el-form-item>
										<el-form-item label="出版日期:">
											<span>{{ props.row.publishDate }}</span>
										</el-form-item>
										<el-form-item label="语言:">
											<span>{{ props.row.language }}</span>
										</el-form-item>
										<el-form-item label="状态:">
											<span>{{ props.row.state }}</span>
										</el-form-item>
										<el-form-item label="借阅人:">
											<span>{{ props.row.readBy }}</span>
										</el-form-item>
									</el-form>
								</el-col>
								<el-col :lg="11" :sm="11" :xs="11" :offset="1">
									<el-form label-position="left" inline>
										<el-form-item label="简介:">
											<span>{{ props.row.textSnippet }}</span>
										</el-form-item>
									</el-form>
								</el-col>
							</el-row>
						</el-container>
					</template>
				</el-table-column>
				<el-table-column prop="title" label="书名">
				</el-table-column>
				<el-table-column prop="authors" label="作者">
				</el-table-column>
				<el-table-column prop="isbn" label="ISBN">
				</el-table-column>
				<el-table-column prop="pageCount" label="总页数">
				</el-table-column>
				<el-table-column prop="textSnippet" label="简介" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="publishedDate" label="发布日期">
				</el-table-column>
				<el-table-column prop="language" :formatter="formatLanguage" label="语言">
				</el-table-column>
				<el-table-column prop="state" :formatter="formatRole" label="读书状态" show-overflow-tooltip>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="100">
					<template slot-scope="scope">
						<el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
						<el-button v-if="scope.row.userNumber" @click="searchLenderClick(scope.row)" type="text"
							size="small">借阅人信息</el-button>
						<!-- <el-button type="text" style="color: red;" @click="open2" size="small">删除</el-button> -->
					</template>
				</el-table-column>
			</el-table>
		</el-main>
		<!-- Form -->

		<el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
			<el-form :model="bookModel">
				<el-row>
					<el-col :lg="12">
						<el-form-item v-if="dialogTitle == '添加读书'" label="ISBN" :label-width="formLabelWidth">
							<div>
								<el-input style="float: left;width: 80%;" v-model="bookModel.isbn" ref="isbnInput"
									@input="change($event)"></el-input>
								<el-button type="infor" @click="getBookByApi()"
									title="该功能为调用<极速数据>平台接口,相应设置在 系统设置->系统设置中设置配置" style="float: right;width: 18%">查询
								</el-button>
							</div>
						</el-form-item>
						<el-form-item v-if="dialogTitle == '编辑读书'" label="ISBN" :label-width="formLabelWidth">
							<el-input v-model="bookModel.isbn" @input="change($event)"></el-input>
						</el-form-item>
						<!-- <el-form-item label="state" :label-width="formLabelWidth">
							<el-input v-model="bookModel.state" @input="change($event)"></el-input>
						</el-form-item> -->
						<el-form-item label="书名" :label-width="formLabelWidth">
							<el-input v-model="bookModel.title" @input="change($event)"></el-input>
						</el-form-item>
						<el-form-item label="作者" :label-width="formLabelWidth">
							<el-input v-model="bookModel.authors" @input="change($event)"></el-input>
						</el-form-item>
						<el-form-item label="发行日期" :label-width="formLabelWidth">
							<el-date-picker v-model="bookModel.publishedDate" style="width:100%" type="date"
								placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="封面" :label-width="formLabelWidth" style="margin-bottom: 12px;">
							<el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
								:show-file-list="false" :on-success="handleAvatarSuccess"
								:before-upload="beforeAvatarUpload">
								<img v-if="bookModel.cover" :src="bookModel.cover" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<el-form-item label="语言" :label-width="formLabelWidth">
							<el-select v-model="bookModel.language" placeholder="请选择活动区域" style="width:100%">
								<el-option label="中文" value="zh-CN"></el-option>
								<!-- <el-option label="区域二" value="beijing"></el-option> -->
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="简介" :label-width="formLabelWidth">
					<el-input type="textarea" v-model="bookModel.textSnippet"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button v-if="dialogTitle == '添加读书'" type="primary" @click="addBookToDb()">确 定</el-button>
				<el-button v-if="dialogTitle == '编辑读书'" type="primary" @click="updateBook()">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog title="借阅人信息" :visible.sync="dialogLenderVisible">
			<el-form :model="lenderModel">
				<el-row>
					<el-col :lg="12">
						<el-form-item label="学号" :label-width="formLabelWidth">
							<label>{{lenderModel.number}}</label>
						</el-form-item>
						<el-form-item label="姓名" :label-width="formLabelWidth">
							<label>{{lenderModel.name}}</label>
						</el-form-item>
						<el-form-item label="班级" :label-width="formLabelWidth">
							<label>{{lenderModel.classes}}</label>
						</el-form-item>
						<el-form-item label="性别" :label-width="formLabelWidth">
							<label v-model="lenderModel.gender === 1">女</label>
							<label v-model="lenderModel.gender === 0">男</label>
						</el-form-item>
						<el-form-item label="借阅时间" :label-width="formLabelWidth">
							<label>{{lenderModel.lendTime}}</label>
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="" :label-width="formLabelWidth" style="margin-bottom: 12px;">
							<img width="100%" :src="lenderModel.headerPath" alt="">
						</el-form-item>

					</el-col>

				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="closeLenderLialog()">关闭</el-button>
			</div>
		</el-dialog>
	</el-container>
</template>

<script>
	// import common from './common'
	export default {
		name: 'books-page',
		data() {
			return {
				pageSize: 99999,
				currentPage: 0,
				dialogTitle: '添加读书',
				/*delete dailog*/
				delDialogVisible: false,
				dialogLenderVisible: false,
				/*upload*/
				imageUrl: '',
				formLabelWidth: '120px',
				bookModel: {
					title: '',
					authors: '',
					cover: '',
					publishedDate: '2021-11-1',
					isbn: '',
					pageCount: 0,
					language: 'zh-CN',
					state: '0',
					readBy: '',
					userNumber: '', //借阅人学号 为空说明读书在馆，被借阅则该值为借阅人的学号。
					lendTime: '', //借阅时间
					textSnippet: ''
				},
				searchmodel: {
					title: '',
					authors: '王小虎',
					publishedDate: '',
					cover: '',
					isbn: '',
					pageCount: '',
					language: '',
					state: '-1',
					readBy: '',
					textSnippet: '',
					pubplace: "", //合肥
					binding: "平装",
					isbn10: "7212058939",
					cip: "2012280296",
					edition: "1版",
					impression: "1",
					format: "23×18",
					class: "K820.7"
				},
				dialogFormVisible: false,
				tableHeight: 800, //document.body.clientHeight - 120,
				tableData: [{
						title: '王小虎自传',
						authors: '王小虎',
						publishedDate: '2016-05-03',
						isbn: 9382048723,
						cover: '',
						pageCount: '998',
						language: '中文',
						state: '在馆',
						readBy: '黄小花',
						textSnippet: '本书共有21章和4个附录,介绍了C#语言的数据类型,操作符,方法,类,接口,异常处理等基本概念,深入讨论了泛型,迭代器,反射,线程和互操作性等高级主题,还介绍了LINQ技术 ...'
					},
					{
						title: '孙子兵法',
						authors: '王小虎',
						cover: '',
						publishedDate: '2016-05-03',
						isbn: 9382048723,
						pageCount: '1518',
						language: '200333',
						state: '外借',
						readBy: '张小兰,黄小花',
						textSnippet: '本书共有21章和4个附录,介绍了C#语言的数据类型,操作符,方法,类,接口,异常处理等基本概念,深入讨论了泛型,迭代器,反射,线程和互操作性等高级主题,还介绍了LINQ技术 ...'
					}
				],
				apiResModel: {
					status: 0,
					msg: "ok",
					result: {
						title: "",
						subtitle: "",
						pic: "",
						author: "",
						summary: "",
						publisher: "", //安徽人民出版社
						pubplace: "", //合肥
						pubdate: "2013-1",
						page: 0,
						price: "29.00",
						binding: "平装",
						isbn: "9787212058937",
						isbn10: "7212058939",
						keyword: "名人－访问记－中国－现代",
						cip: "2012280296",
						edition: "1版",
						impression: "1",
						language: "",
						format: "23×18",
						class: "K820.7"
					}
				},
				settingModel: {
					appkey: '7d3b18e6794fbd95',
					url: 'https://api.jisuapi.com/isbn/query',
					officialAddress: 'https://www.jisuapi.com/'
				},
				lenderModel: {
					sequenceNumber: 1,
					id: this.$uuid.v1(),
					name: '',
					number: '',
					headerPath: '',
					gender: '0',
					classes: '',
					books: '',
					lendTime: ''
				}
			}
		},
		created: function() {
			console.log()
			this.getBooks()
		},
		methods: {
			getBookByApi() {
				var _self = this
				var _self_ = this
				this.$Settingstore.findOne({}, function(err, docs) {
					console.log(docs)
					if (docs) {
						_self.settingModel = docs
						if (_self.bookModel.isbn.length < 10) {
							_self.$message.error('错了哦，请输入10-13位的ISBN码，在书的背面。');
						} else {
							var url = _self.settingModel.url + '?appkey=' + _self.settingModel.appkey + '&isbn=' + _self.bookModel.isbn
							console.log(url)
							_self_.$http.get(url, {}).then(function(res) {
								_self.apiResModel = res.data
								_self.bookModel.isbn = _self.apiResModel.result.isbn
								_self.bookModel.title = _self.apiResModel.result.title
								_self.bookModel.authors = _self.apiResModel.result.author
								_self.bookModel.publishedDate = _self.apiResModel.result.pubdate
								_self.bookModel.pageCount = _self.apiResModel.result.page
								_self.bookModel.state = 1
								_self.bookModel.textSnippet = _self.apiResModel.result.summary
								_self.bookModel.pubplace = _self.apiResModel.result.pubplace, //合肥
									_self.bookModel.binding = _self.apiResModel.result.binding //平装
								_self.bookModel.isbn10 = _self.apiResModel.result.isbn10
								_self.bookModel.cip = _self.apiResModel.result.cip //2012280296
								_self.bookModel.edition = _self.apiResModel.result.edition //1版
								_self.bookModel.impression = _self.apiResModel.result.impression //1
								_self.bookModel.format = _self.apiResModel.result.format //23×18
								_self.bookModel.class = _self.apiResModel.result.class //K820.7
								_self.bookModel.readBy = ''
								_self.commonFunction.downloadImg(_self.apiResModel
									.result.pic).then(function(base64data) {
									_self.bookModel.cover = base64data
								})
							}, function(err) {
								console.log(err)
							})
						}
					}
				})
			},
			formatRole(row, column) {
				return row.state == '1' ? "在馆" : "外借";
			},
			formatLanguage(row, column) {
				return row.language == 'zh-CN' ? "中文" : "其它";
			},
			getBooks() {
				var _self = this
				var regexp = new RegExp(_self.searchmodel.isbn, "i");
				var regexpNumber = new RegExp(_self.searchmodel.title, "i");
				var filter = {
					$and: []
				}
				if (_self.searchmodel.isbn) {
					filter.$and.push({
						isbn: {
							$regex: regexp
						}
					})
				}
				if (_self.searchmodel.title) {
					filter.$and.push({
						title: {
							$regex: regexpNumber
						}
					})
				}
				if (_self.searchmodel.state != -1) {
					filter.$and.push({
						state: Number(_self.searchmodel.state)
					})
				}
				this.$BookDatastore.find(filter).skip(this.currentPage * this.pageSize).limit(this.pageSize).exec(function(
					err, docs) {
					//remove all book
					// for (var i = 0; i < docs.length; i++) {
					// 	docs[i].userNumber = ''
					// 	docs[i].state = 1
					// 	_self.$BookDatastore.update({
					// 				_id: docs[i]._id
					// 		}, {$set:docs[i]},
					// 		function(err,dc) {

					// 		})
					// }
					console.log(docs)
					_self.tableData = docs
				})
			},
			addBook() {
				this.dialogTitle = '添加读书'
				this.dialogFormVisible = true
				this.bookModel = {
					title: '',
					authors: '',
					cover: '',
					publishedDate: '2021-11-1',
					isbn: '',
					pageCount: 0,
					language: 'zh-CN',
					state: '0',
					readBy: '',
					textSnippet: ''
				}
			},
			handleClick(row) {
				this.dialogTitle = '编辑读书'
				console.log(row);
				this.bookModel = row
				this.dialogFormVisible = true
			},
			searchLenderClick(row) {
				var _self = this
				this.dialogLenderVisible = true;
				// this.$LendDatastore.findOne({
				// 	"user.number": row.userNumber,
				// 	"books.id":row.id
				// },function(err,docs){
				// 	debugger
				// })
				this.$UserDatastore.findOne({
					"number": row.userNumber
				}, function(err, docs) {
					if (docs) {
						_self.lenderModel = docs
						_self.lenderModel.lendTime = _self.commonFunction.timestampToTime(row.lendTime)
					}
				})
			},
			closeLenderLialog() {
				this.dialogLenderVisible = false;
			},
			change(e) {
				this.$forceUpdate()
			},
			/*upload*/
			handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			/*delete dialog*/
			open2() {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			addBookToDb() {
				var _self = this
				this.$BookDatastore.insert(this.bookModel, function(err, doc) {
					console.log('inserted:', doc)
					_self.getBooks()
					_self.dialogFormVisible = false
				})

			},
			updateBook() {
				var _self = this
				this.$BookDatastore.update({
					_id: this.bookModel._id
				}, {
					$set: this.bookModel
				}, function(err, docs) {
					_self.dialogFormVisible = false
				})
			}
		},
		watch: {
			tableHeight(val) {
				console.log('sdfasdf')
				// 为了避免频繁触发resize函数导致页面卡顿，使用定时器
				if (!this.timer) {
					// 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
					this.tableHeight = val
					console.log("kkkkk" + val)
					this.timer = true
					let that = this
					setTimeout(function() {
						// 打印screenWidth变化的值
						console.log(that.tableHeight)
						that.timer = false
					}, 400)
				}
			}
		},
		mounted() {
			const that = this
			window.onresize = () => {
				return (() => {
					window.screenHeight = document.body.clientHeight
					that.tableHeight = window.screenHeight - 180
				})()
			}
		}
	}
</script>

<style scoped="scoped">
	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {

		color: #99a9bf;
	}

	.demo-table-expand .el-form-item label {
		width: 100% !important;
		font-size: 20px !important;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}

	.dialog-form .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}

	/* upload */
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 170px;
		height: 170px;
		line-height: 170px;
		text-align: center;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
	}

	.avatar {
		width: 170px;
		height: 170px;
		display: block;
	}
</style>
